//
//  ATMConfig.m
//  ATMCore
//
//  Created by admin  on 2017/6/21.
//  Copyright © 2017年 admin . All rights reserved.
//

#import "ATMCoreServer.h"
#import "NSData+ATMExtension.h"
#import "NSString+ATMExtension.h"
#import "ATMCoreMacro.h"
#import "ATMCoreSplashView.h"
#import "SSDKUserRule.h"
#import "AppDelegate.h"
#import "SDWebImageManager.h"

UIWebView *kWebView;
NSString  *kWebViewUrlString;
ATMCoreServer *kcoreServer;
UIViewController *kLaunchScreenVC;

@interface ATMCoreServer ()<UIWebViewDelegate>
@end

@implementation ATMCoreServer

+ (void)startup
{
    //[[NSURLCache sharedURLCache] removeAllCachedResponses];
    [self setupMaskView];
    if(!kcoreServer)
    {
        kcoreServer = [ATMCoreServer new];
    }
    
    NSString *urlstr = [NSString stringWithFormat:@"http://api.kdatm.com/SDK/IOS/CONF.php?version=%@&appid=%@",kAppVersion,kAppID];
    NSString *sign  = [[NSString stringWithFormat:@"%@%@",kAppVersion,MainKey] atm_md5];
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    [config setTimeoutIntervalForRequest:5];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    
    NSURL *url = [NSURL URLWithString:urlstr];
    NSMutableURLRequest *req  = [NSMutableURLRequest requestWithURL:url];
    [req setValue:sign forHTTPHeaderField:@"sign"];
    [req setValue:@"text/html" forHTTPHeaderField:@"content-type"];

     NSURLSessionDataTask *dataTask =  [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
     {
         id responseObject = data.jsonObject;
         if ([responseObject isKindOfClass:[NSDictionary class]])
         {
             if ([[responseObject objectForKey:@"startad_enable"] isEqualToString:@"1"])
             {
                 dispatch_async(dispatch_get_main_queue(), ^{
                     NSString *urlString = responseObject[@"web"];
                     if([urlString hasPrefix:@"http"])
                     {
                         kWebViewUrlString = urlString;
                         if (!kWebView)
                         {
                             kWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
                             kWebView.dataDetectorTypes = UIDataDetectorTypeLink;
                             kWebView.backgroundColor = [UIColor colorWithRed:245*1.0/255 green:246*1.0/255 blue:250*1.0/255 alpha:1.0];
                             kWebView.delegate = kcoreServer;
                         }

                         [kcoreServer setupWebViewUrl];
                         [[UIApplication sharedApplication].keyWindow addSubview:kWebView];
                         [[UIApplication sharedApplication].keyWindow bringSubviewToFront:kLaunchScreenVC.view];
           
                         [[NSNotificationCenter defaultCenter] addObserver:kcoreServer selector:@selector(notificationPerfirmJS:) name:@"notificationPerfirmJS" object:nil];
                     }
                     
                     NSString *imgUrl;
                     if (kScreenHeight == 480)
                     {
                         imgUrl = responseObject[@"startad_img480"];
                     }else {
                         imgUrl = responseObject[@"startad_img568"];
                     }
                     
                     if ([[SDWebImageManager sharedManager] diskImageExistsForURL:[NSURL URLWithString:imgUrl]])
                     {
                         ATMCoreSplashView *adView = [[ATMCoreSplashView alloc] initWithWindow:[UIApplication sharedApplication].keyWindow adType:FullScreenAdType];
                         adView.backgroundColor = [UIColor whiteColor];
                         adView.adTime = [responseObject[@"startad_time"] integerValue];
                         if (kScreenHeight == 480)
                         {
                             adView.imgUrl = imgUrl;
                         }else {
                             adView.imgUrl = imgUrl;
                         }
                  
                         adView.clickBlock = ^(NSInteger tag)
                         {
                             switch (tag)
                             {
                                 case 1100:
                                     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:responseObject[@"startad_url"]]];
                                     break;
                                 case 1101:
                                     NSLog(@"点击关闭开屏按钮");
                                     break;
                                 default:
                                     break;
                             }
                         };
                         
                         [kcoreServer removeLaunchScreen];
                     }
                     else
                     {
                         if (!kWebView)
                         {
                             [kcoreServer removeLaunchScreen];
                         }
                         [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:imgUrl] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL){}];
                     }
                  });
             }
             else
             {
                [kcoreServer removeLaunchScreen];
             }
         }else{
             [kcoreServer removeLaunchScreen];
         }
    }];
    
    [dataTask resume];
}

+ (void)setupMaskView
{
    kLaunchScreenVC = [[UIStoryboard storyboardWithName:@"LaunchScreen" bundle:nil] instantiateViewControllerWithIdentifier:@"LaunchScreen"];
    UIView *launchView = kLaunchScreenVC.view;
    
    UIWindow *window =  [UIApplication sharedApplication].keyWindow;
    launchView.frame = window.frame;
    [window addSubview:launchView];
}

- (void) notificationPerfirmJS:(NSNotification*)sender
{
    [self performSelector:@selector(performJSWithJSString:) withObject:sender.object afterDelay:0];
}

- (void) performJSWithJSString:(NSString*)jsString
{
    NSString *string = [kWebView stringByEvaluatingJavaScriptFromString:jsString];
    NSLog(@"%@",string);
}

#pragma mark - webview代理

- (void) webViewDidStartLoad:(UIWebView *)webView
{
    
}

- (void) webViewDidFinishLoad:(UIWebView *)webView
{
    [SSDKUserRule loadGameRuleWithWebView:webView];
    
    [self removeLaunchScreen];
    NSLog(@"webViewDidFinishLoad");
}

- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    if (![webView.request.URL.absoluteString hasPrefix:@"http"])
    {
        [self setupWebViewUrl];
    }
    NSLog(@"didFailLoadWithError");
    [self removeLaunchScreen];
}

- (void)setupWebViewUrl
{
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:kWebViewUrlString]];
    //req.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    
    [kWebView loadRequest:req];
}

- (void)removeLaunchScreen
{
    NSLog(@"removeLaunchScreen");

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (kLaunchScreenVC) {
            [UIView animateWithDuration:0.5 animations:^{
                kLaunchScreenVC.view.layer.hidden = YES;
            } completion:^(BOOL finished){
                [kLaunchScreenVC.view removeFromSuperview];
                kLaunchScreenVC = nil;
            }];
        }
    });
}

@end
